#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "parse.h"

// echo abc
void test_parse_cmd_1()
{
    struct cmd cmd;
    char line[] = "echo abc xyz";
    parse_cmd(line, &cmd);

    assert(cmd.argc == 3);
    assert(strcmp(cmd.argv[0], "echo") == 0);
    assert(strcmp(cmd.argv[1], "abc") == 0);
    assert(strcmp(cmd.argv[2], "xyz") == 0);
    assert(cmd.argv[3] == NULL);
}

// echo abc >log
void test_parse_cmd_2()
{
    struct cmd cmd;
    char line[] = "echo abc >log";
    parse_cmd(line, &cmd);

    assert(cmd.argc == 2);
    assert(strcmp(cmd.argv[0], "echo") == 0);
    assert(strcmp(cmd.argv[1], "abc") == 0);
    assert(cmd.argv[2] == NULL);
    assert(strcmp(cmd.output, "log") == 0);
}

// cat /etc/passwd | wc -l
void test_parse_pipe_cmd_1()
{
    struct cmd cmdv[MAX_CMDC];
    char line[] = "cat /etc/passwd | wc -l";
    int cmdc, i;

    for (i = 0; i < MAX_CMDC; ++i) {
	    cmdv[i].argc = 0;
	    cmdv[i].input = NULL;
	    cmdv[i].output = NULL;
    }
    cmdc = parse_pipe_cmd(line, cmdv);

    assert(cmdc == 2);
    assert(cmdv[0].argc == 2);
    assert(strcmp(cmdv[0].argv[0], "cat") == 0);
    assert(strcmp(cmdv[0].argv[1], "/etc/passwd") == 0);
    assert(cmdv[0].argv[2] == NULL);
    assert(cmdv[1].argc == 2);
    assert(strcmp(cmdv[1].argv[0], "wc") == 0);
    assert(strcmp(cmdv[1].argv[1], "-l") == 0);
    assert(cmdv[1].argv[2] == NULL);
}

// cat <input | sort | cat >output
void test_parse_pipe_cmd_2()
{
    struct cmd cmdv[MAX_CMDC];
    char line[] = "cat <input | sort | cat >output";
    int cmdc, i;

    for (i = 0; i < MAX_CMDC; ++i) {
	    cmdv[i].argc = 0;
	    cmdv[i].input = NULL;
	    cmdv[i].output = NULL;
    }
    cmdc = parse_pipe_cmd(line, cmdv);

    assert(cmdc == 3);
    assert(cmdv[0].argc == 1);
    assert(strcmp(cmdv[0].argv[0], "cat") == 0);
    assert(cmdv[0].argv[1] == NULL);
    assert(strcmp(cmdv[0].input, "input") == 0);
    assert(cmdv[1].argc == 1);
    assert(strcmp(cmdv[1].argv[0], "sort") == 0);
    assert(cmdv[1].argv[1] == NULL);
    assert(cmdv[2].argc == 1);
    assert(strcmp(cmdv[2].argv[0], "cat") == 0);
    assert(cmdv[2].argv[1] == NULL);
    assert(strcmp(cmdv[2].output, "output") == 0);
}
